<?php
declare (strict_types = 1);

namespace app\controller\api\v1\user\order;

use app\controller\api\ApiController;
use app\service\logic\common\order\OrderCourseService;
use app\validate\common\course\CourseValidate;
use app\validate\common\order\MultiValidate;
use Carbon\Carbon;
use think\App;
use think\Request;
use think\response\Json;
use think\db\exception\DbException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class CourseController extends ApiController
{
    protected $service;

    public function __construct(App $app, OrderCourseService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 测试记录
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(): Json
    {
        $params = $this->request->param();
        $search_fields = $this->service->getSearchColumn();
        $search = request()->only($search_fields);

        $this->validate($params, CourseValidate::class . '.index');
        $user = $this->request->middleware('user');
        $search['user_id'] = $user['id'];
        $search['state'] = 1;
        $search['type'] = 3;
        // $search['expired_at'] = 1;

        $fun = function ($model) {
            $currentAt = Carbon::now()->timestamp;
            if (0 != $model['expired_at'] && $model['expired_at'] <= $currentAt) {
                $model['is_expired'] = 1; // 已过期
            } else {
                $model['is_expired'] = 2; // 未过期
            }
            return $model;
        };
        $result = $this->service->getAppList($params, $search_fields, $search, [], $fun);
        return amis($result);
    }

    /**
     * 显示资源
     *
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws \app\exception\LogicException
     */
    public function read(Request $request): Json
    {
        $params = $request->param();
        $this->validate($params, CourseValidate::class . '.read');

        $result = $this->service->read($params);
        return amis($result);
    }
}
